package command

import (
	"context"
	"fmt"
	"syscall"
	"time"

	"github.com/kardianos/service"
	"github.com/toolkits/file"
)

var (
	Name        = "prober"
	displayName = "prober"
	description = "prober"
	SRV         service.Service
	ctx         context.Context
)

// 模块初始化
func init() {
	s, err := initSrv()
	if err != nil {
		e := fmt.Errorf("can not create prober server,error:%v", err)
		panic(e)
	}
	SRV = *s

	ctx = context.TODO()
}

// 初始化服务
func initSrv() (*service.Service, error) {
	installedPath := file.SelfDir()
	svcConfig := &service.Config{
		Name:             Name,
		DisplayName:      displayName,
		Description:      description,
		WorkingDirectory: installedPath,
		UserName:         "root",
		Arguments:        []string{"run", "-d", "1"},
		Dependencies: []string{
			"After=network-online.target",
			"Wants=network-online.target",
		},
	}

	prg := &program{}
	srv, err := service.New(prg, svcConfig)
	if err != nil {
		fmt.Printf("Failed to New %v service,error:%v\n", Name, err)
		return nil, err
	}

	return &srv, nil
}

type program struct{}

func (p program) Start(s service.Service) error {
	fmt.Println(s.String() + " started")
	go p.run()
	return nil
}

func (p program) Stop(s service.Service) error {
	fmt.Println(s.String() + " stopped")
	signals <- syscall.SIGSTOP
	return nil
}

func operService(action string) error {
	switch action {
	case "install":
		err := SRV.Install()
		if err != nil {
			fmt.Printf("Failed to install %v,error:%v\n", Name, err)
			return err
		} else {
			fmt.Printf("Succeed to install service %v\n", Name)
		}
	case "uninstall":
		SRV.Stop()
		err := SRV.Uninstall()
		if err != nil {
			fmt.Printf("Failed to install %v,error:%v\n", Name, err)
			return err
		} else {
			fmt.Printf("Succeed to install service %v\n", Name)
		}
	case "start":
		err := SRV.Start()
		if err != nil {
			fmt.Printf("Failed to install %v,error:%v\n", Name, err)
			return err
		} else {
			fmt.Printf("Succeed to install service %v\n", Name)
		}
	case "stop":
		err := SRV.Stop()
		if err != nil {
			fmt.Printf("Failed to install %v,error:%v\n", Name, err)
			return err
		} else {
			fmt.Printf("Succeed to install service %v\n", Name)
		}

	default:
		fmt.Println("install/uninstall/start/stop service")
	}
	return nil
}

func (p program) run() {
	go startProberService(times, duration)
}

func startProberService(times, duration int) {
	x := 1
	if duration <= 0 {
		fmt.Println("duration must be greater than 0")
		signals <- syscall.SIGSTOP
		return
	}
	for {
		if times > 0 && x > times {
			signals <- syscall.SIGSTOP
			break
		}
		<-time.After(time.Minute * time.Duration(duration))
		FetchRPT()
		x += 1
	}
}
